import BaseBarChartComponent from "./base-bar-chart.js";
// 堆叠条形图组件（横向）
class StackedBarHorizontalChart extends BaseBarChartComponent {
    // 重写观察的属性列表
    static get observedAttributes() {
        const parentAttributes = super.observedAttributes;
        return [
            ...parentAttributes,
        ];
    }

    // 重写默认配置，严格匹配样例
    getDefaultConfig() {
        const parentConfig = super.getDefaultConfig();

        // 图例配置
        parentConfig.legendAttrs = [
            ...parentConfig.legendAttrs,
            ['legend-show_radio', true],
            ['legend-top_slider', 'top'],
            ['legend-left_slider', 'center'],
            ['legend-orient_select', 'horizontal']
        ];

        // X轴配置（值轴）
        parentConfig.xAxisAttrs = [
            ...parentConfig.xAxisAttrs ,
            ['xaxis-type_text', 'value'],
            ['xaxis-axisline-show_radio', false],
            ['xaxis-splitline-show_radio', true],
            ['xaxis-splitline-linestyle-type_select', 'solid']
        ];

        // Y轴配置（分类轴）
        parentConfig.yAxisAttrs = [
            ...parentConfig.yAxisAttrs,
            ['yaxis-type_text', 'category'],
            ['yaxis-data_array', JSON.stringify(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])],
            ['yaxis-axisline-show_radio', false],
            ['yaxis-axistick-show_radio', true]
        ];

        // 系列配置
        parentConfig.seriesAttrs = [
            ...parentConfig.seriesAttrs,
            ['series-show-legend_radio', true],
            ['series-show-labels_radio', true],
            ['series-label-position_select', 'insideRight'],
            // 各系列颜色配置（使用ECharts默认配色方案）
            ['series-color-direct_colorpicker', '#5470c6'],
            ['series-color-mail_colorpicker', '#91cc75'],
            ['series-color-affiliate_colorpicker', '#fac858'],
            ['series-color-video_colorpicker', '#ee6666'],
            ['series-color-search_colorpicker', '#73c0de']
        ];

        return parentConfig;
    }

    // 重写生成系列配置，精确匹配堆叠关系
    generateSeries(dataDemo, seriesConfig) {
        const showLabels = seriesConfig.showLabels !== false;
        const labelPosition = seriesConfig.labelPosition || 'insideRight';

        // 获取所有系列 key
        const seriesKeys = dataDemo.map(item => Object.keys(item)[0]);

        // 提取分类（取第一个系列的 name 作为全局 xAxis 使用）
        this.currentCategories = dataDemo[0][seriesKeys[0]].map(d => d.name);

        // 获取父类默认渐变色
        const gradients = this.getDefaultGradients();

        // 构造 series
        return seriesKeys.map((key, idx) => {
            const values = dataDemo.find(obj => obj[key])[key].map(d => d.value);

            // 对应渐变色
            const gradient = gradients[idx % gradients.length];

            return {
                name: key,
                type: 'bar',
                stack: 'total',
                label: {
                    show: showLabels,
                    position: labelPosition,
                    formatter: '{c}'
                },
                emphasis: { focus: 'series' },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: gradient.start },
                        { offset: 1, color: gradient.end }
                    ])
                },
                data: values
            };
        });
    }



    // 重写默认数据
    getDefaultData() {
        // 返回与样例一致的数据源结构
        return [{
            "销售":[{"name":"衬衫","value":5}, {"name":"羊毛衫","value":20},{"name":"雪纺衫","value":36}, {"name":"裤子","value":10}, {"name":"高跟鞋","value":10}, {"name":"袜子","value":10}]
        },{
            "销售1":[{"name":"衬衫","value":11}, {"name":"羊毛衫","value":21},{"name":"雪纺衫","value":31}, {"name":"裤子","value":11}, {"name":"高跟鞋","value":21}, {"name":"袜子","value":21}]
        }];
    }

    // 重写渲染方法，确保配置完全匹配
    renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig, data = null) {
        const dataDemo = data || this.getDefaultData();

        // 自动生成 series
        const series = this.generateSeries(dataDemo, seriesConfig);

        // 设置 yAxis 为动态分类
        yAxisConfig.data = this.currentCategories || [];
        yAxisConfig.type = 'category';
        // tooltip 保持 shadow 样式
        const tooltipConfig = {
            trigger: 'axis',
            axisPointer: { type: 'shadow' }
        };

        legendConfig.show = seriesConfig.showLegend !== false;
        titleConfig.show = false;

        super.renderChart(
            { ...seriesConfig, tooltip: tooltipConfig, series },
            titleConfig,
            gridConfig,
            xAxisConfig,
            yAxisConfig,
            legendConfig,
            dataDemo
        );
    }


    // 处理属性变化
    handleAttributeChange(name, value, currentOptions) {
        super.handleAttributeChange(name, value, currentOptions);

        if ([
            'show-legend_radio',
            'show-labels_radio',
            'label-position_select',
            'color-direct_colorpicker',
            'color-mail_colorpicker',
            'color-affiliate_colorpicker',
            'color-video_colorpicker',
            'color-search_colorpicker'
        ].includes(name)) {
            this.reRenderChart();
        }
    }

    // 重新渲染图表
    reRenderChart() {
        const { buildConfig } = window.attributeUtils;
        const config = this.getDefaultConfig();

        const seriesConfig = buildConfig(this, config.seriesAttrs);
        const titleConfig = buildConfig(this, config.titleAttrs);
        const gridConfig = buildConfig(this, config.gridAttrs);
        const xAxisConfig = buildConfig(this, config.xAxisAttrs);
        const yAxisConfig = buildConfig(this, config.yAxisAttrs);
        const legendConfig = buildConfig(this, config.legendAttrs);

        this.renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig);
    }
}

// 注册自定义元素
customElements.define('stacked-horizontal-bar-chart', StackedBarHorizontalChart);
